import glob
import os
import threading
import time
from tkinter import ttk, filedialog
import tkinter as tk
from tkinter import messagebox

from libs.doc import handler_docx
from libs.excel import add_watermark_to_excel
from libs.img import add_img_watermark
from libs.pdf import add_watermark
from tkinter import scrolledtext

from libs.ppt import add_ppt_watermark


class MainApp:
    def __init__(self, root):
        self.root = root
        self.f1 = ""
        self.f2 = ""
        self.text = ""
        self.root.title("office数据水印-四川凌空")
        self.root.geometry("850x650")
        self.root.config(bg="#f4f4f9")

        # 设置字体和颜色
        self.font = ("Arial", 12)
        self.button_font = ("Arial", 10)
        self.bg_color = "#cccccc"
        self.fg_color = "#ffffff"

        # 文件夹选择器1
        self.folder_path1_label = ttk.Label(root, text="数据导入文件夹:", font=self.font, background="#f4f4f9")
        self.folder_path1_label.grid(row=0, column=0, padx=15, pady=10, sticky="w")
        self.folder_path1_button = ttk.Button(root, text="数据导入文件夹", command=self.select_folder1, style="TButton")
        self.folder_path1_button.grid(row=0, column=1, padx=10)

        # 显示文件夹路径1
        self.folder_path1_var = tk.StringVar()
        self.folder_path1_entry = ttk.Entry(root, textvariable=self.folder_path1_var, width=30, font=self.font)
        self.folder_path1_entry.grid(row=0, column=2, padx=10, pady=10)


        # 文件夹选择器2
        self.folder_path2_label = ttk.Label(root, text="数据导出文件夹:", font=self.font, background="#f4f4f9")
        self.folder_path2_label.grid(row=1, column=0, padx=15, pady=10, sticky="w")
        self.folder_path2_button = ttk.Button(root, text="数据导出文件夹", command=self.select_folder2, style="TButton")
        self.folder_path2_button.grid(row=1, column=1, padx=10)

        # 显示文件夹路径2
        self.folder_path2_var = tk.StringVar()
        self.folder_path2_entry = ttk.Entry(root, textvariable=self.folder_path2_var, width=30, font=self.font)
        self.folder_path2_entry.grid(row=1, column=2, padx=10, pady=10)

        # 输入框
        self.input_label = ttk.Label(root, text="请输入水印文字:", font=self.font, background="#f4f4f9")
        self.input_label.grid(row=2, column=0, padx=15, pady=10, sticky="w")
        self.input_entry = ttk.Entry(root, width=30, font=self.font)
        self.input_entry.grid(row=2, column=1, columnspan=2, padx=10, pady=10)

        # 确定按钮
        self.submit_button = ttk.Button(root, text="确定", command=self.submit, style="TButton")
        self.submit_button.grid(row=3, column=1, columnspan=2, pady=20)

        # 创建一个可以显示多行文本的滚动文本框
        self.log_box = scrolledtext.ScrolledText(self.root, width=115, height=20, wrap=tk.WORD)

        # 使用 pack() 管理布局
        self.log_box.grid(row=4, column=0,columnspan=4, padx=10, pady=10)

        # 设置文本框为只读模式
        self.log_box.config(state=tk.DISABLED)


        # 配置样式
        self.style = ttk.Style()
        self.style.configure("TButton",
                             font=("Arial", 12),
                             padding=10,
                             background=self.bg_color,
                             foreground=self.fg_color,
                             focuscolor=self.bg_color)
        self.style.map("TButton",
                       background=[("active", "#cccccc")])

    def select_folder1(self):
        folder_path = filedialog.askdirectory()
        if folder_path:
            self.folder_path1_var.set(folder_path)

    def select_folder2(self):
        folder_path = filedialog.askdirectory()
        if folder_path:
            self.folder_path2_var.set(folder_path)

    def submit(self):
        folder1 = self.folder_path1_var.get()
        folder2 = self.folder_path2_var.get()
        input_text = self.input_entry.get()

        # 如果文件夹路径为空，弹出提示框
        if not folder1 or not folder2 or not input_text:
            messagebox.showwarning("输入错误", "请确保所有字段都已填写！")
            return

        self.f1=folder1
        self.f2=folder2
        self.text=input_text

        log_thread = threading.Thread(target=self.scan_office_file)
        log_thread.start()




    def add_log(self, content):
        # 获取当前时间并格式化
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        log_entry = f"[{current_time}] {content}"
        # 启用编辑状态
        self.log_box.config(state=tk.NORMAL)

        # 插入新日志，并滚动到最新行
        self.log_box.insert(tk.END, log_entry + '\n')
        self.log_box.yview(tk.END)
        # 禁用编辑状态
        self.log_box.config(state=tk.DISABLED)


    def scan_office_file(self):
        self.add_log("扫描文件开始")
        docx_files = glob.glob(os.path.join(self.f1, '**', '*.docx'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.doc'), recursive=True)
        pdf_files = glob.glob(os.path.join(self.f1, '**', '*.pdf'), recursive=True)
        xlsx_files = glob.glob(os.path.join(self.f1, '**', '*.xlsx'), recursive=True)
        pptx_files = glob.glob(os.path.join(self.f1, '**', '*.pptx'), recursive=True)
        img_files = glob.glob(os.path.join(self.f1, '**', '*.png'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.jpeg'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.jpg'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.jfif'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.webp'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.tif'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.heic'), recursive=True)+glob.glob(os.path.join(self.f1, '**', '*.bmp'), recursive=True)
        try:
            self.add_log("docx文件数:"+ f"{len(docx_files)}")
            for file in docx_files:
                try:
                    output = file.replace(self.f1,self.f2)
                    handler_docx(file,output,self.text)
                    self.add_log( os.path.normpath(output)+" 处理完成")
                except Exception as e:
                    print(e)
                    self.add_log( os.path.normpath(file)+"处理失败")

            self.add_log("pdf文件数:"+ f"{len(pdf_files)}")
            for file in pdf_files:
                try:
                    output = file.replace(self.f1,self.f2)
                    folder_path = os.path.dirname(output)
                    if not os.path.exists(folder_path):
                        os.makedirs(folder_path)
                    add_watermark(file,output,self.text)
                    self.add_log( os.path.normpath(output)+" 处理完成")
                except Exception as e:
                    print(e)
                    self.add_log( os.path.normpath(file)+"处理失败")

            self.add_log("xlsx文件数:"+f"{len(xlsx_files)}")
            for file in xlsx_files:
                try:
                    output = file.replace(self.f1,self.f2)
                    add_watermark_to_excel(file,output,self.text)
                    self.add_log( os.path.normpath(output)+" 处理完成")
                except Exception as e:
                    print(e)
                    self.add_log( os.path.normpath(file)+"处理失败")

            self.add_log("pptx文件数:"+f"{len(pptx_files)}")
            for file in pptx_files:
                try:
                    output = file.replace(self.f1,self.f2)
                    add_ppt_watermark(file,output,self.text)
                    self.add_log( os.path.normpath(output)+" 处理完成")
                except Exception as e:
                    print(e)
                    self.add_log( os.path.normpath(file)+"处理失败")

            self.add_log("图片文件数:"+f"{len(img_files)}")
            for file in img_files:
                try:
                    output = file.replace(self.f1,self.f2)
                    add_img_watermark(file,output,self.text)
                    self.add_log( os.path.normpath(output)+" 处理完成")
                except Exception as e:
                    print(e)
                    self.add_log( os.path.normpath(file)+"处理失败")
        except:
            pass
        self.add_log("文件全部处理完成")
